package cn.xuchunh.campusbbs.ui.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.adapter.PersonAdapter;
import cn.xuchunh.campusbbs.base.BaseRecyclerViewAdapter;
import cn.xuchunh.campusbbs.bean.Indicator;
import cn.xuchunh.campusbbs.bean.User;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.net.SimpleXJsonListener;
import cn.xuchunh.campusbbs.ui.activities.AlbumActivity;
import cn.xuchunh.campusbbs.ui.activities.UserActivity;
import cn.xuchunh.campusbbs.ui.activities.UserProfileActivity;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.utils.JsonParser;

/**
 * Created by XuChunH on 2015/10/18.
 */
public class PersonFragment extends SimpleIndicatorListFragment<ViewHolder, Indicator> {

    private int userId = getUser().getUserId();

    public static PersonFragment newInstance(int userId) {

        Bundle args = new Bundle();
        args.putInt(IntentParamsKey.USER_ID, userId);
        PersonFragment fragment = new PersonFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void loadDataFromCache() {
        List<Indicator> indicatorList = new ArrayList<>();
        indicatorList.add(new Indicator(Indicator.TYPE_DIVIDER));
        indicatorList.add(new Indicator("我的资料", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon5)));
        indicatorList.add(new Indicator("我的相册", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon4)));
        indicatorList.add(new Indicator(Indicator.TYPE_DIVIDER));
        indicatorList.add(new Indicator("我的好友", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        indicatorList.add(new Indicator("我的关注", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        indicatorList.add(new Indicator("我的粉丝", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        indicatorList.add(new Indicator(Indicator.TYPE_DIVIDER));
        indicatorList.add(new Indicator("我的发表", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        indicatorList.add(new Indicator("我的回复", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        indicatorList.add(new Indicator("我的收藏", Uri.parse("res://" + getActivity().getPackageName() + "/" + R.drawable.mc_forum_squre_icon6)));
        loadDataFinished(true, indicatorList);
        getRefreshLayout().setEnabled(true);
        getRefreshLayout().setRefreshing(true);
        loadUserInfo();
    }

    @Override
    protected BaseRecyclerViewAdapter createAdapter() {
        return new PersonAdapter(getActivity());
    }

    @Override
    public String getCacheKey() {
        return null;
    }

    private void loadUserInfo() {
        HttpRequestManager.getInstance(getActivity())
                .loadUserInfo(userId, jsonListener, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        getRefreshLayout().setRefreshing(false);
                        showToast(error.getMessage());
                    }
                }, getVolleyTag());
    }

    @Override
    public String getVolleyTag() {
        return PersonFragment.class.getSimpleName();
    }

    @Override
    public void onItemClick(int position, View item) {
        if (getAdapter().getItemViewType(position) == PersonAdapter.TYPE_HEADER) {
            UserActivity.launch(getActivity(), userId);
        } else {
            Indicator indicator = getAdapter().getItem(position - 1);
            if (indicator.getType() == Indicator.TYPE_INDICATOR) {
                switch (position) {
                    case 2:
                        startActivity(new Intent(getActivity(), UserProfileActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), AlbumActivity.class));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    protected void handleArgs(Bundle args) {
        super.handleArgs(args);
        if (args != null) {
            userId = args.getInt(IntentParamsKey.USER_ID, getUser().getUserId());
        }
    }

    private SimpleXJsonListener<User> jsonListener = new SimpleXJsonListener<User>() {
        @Override
        public User parseData(JSONObject jsonObject) throws Exception {
            User user = new User();
            user.setUserId(userId);
            user.setFlag(jsonObject.optInt(JsonKey.FLAG));
            user.setBlack(jsonObject.optInt(JsonKey.IS_BLACK) != 0);
            user.setFollow(jsonObject.optInt(JsonKey.IS_FOLLOW) != 0);
            user.setFriend(jsonObject.optInt(JsonKey.ISFRIEND) != 0);
            user.setAvatar(jsonObject.optString(JsonKey.ICON));
            user.setUserName(jsonObject.optString(JsonKey.NAME));
            user.setEmail(jsonObject.optString(JsonKey.EMAIL));
            user.setStatus(jsonObject.optInt(JsonKey.STATUS));
            user.setGender(jsonObject.optInt(JsonKey.GENDER));
            user.setCredits(jsonObject.optInt(JsonKey.CREDITS));
            user.setExtCredits(jsonObject.optInt(JsonKey.GOLD_NUM));
            user.setTopicNum(jsonObject.optInt(JsonKey.TOPIC_NUM));
            user.setPhotoNum(jsonObject.optInt(JsonKey.PHOTO_NUM));
            user.setReplyPostsNum(jsonObject.optInt(JsonKey.REPLY_POSTS_NUM));
            user.setEssenceNum(jsonObject.optInt(JsonKey.ESSENCE_NUM));
            user.setFriendNum(jsonObject.optInt(JsonKey.FRIEND_NUM));
            user.setFollowNum(jsonObject.optInt(JsonKey.FOLLOW_NUM));
            user.setLevel(jsonObject.optInt(JsonKey.LEVEL));
            user.setUserTitle(jsonObject.optString(JsonKey.USERTITLE));
            JSONObject body = jsonObject.optJSONObject(JsonKey.BODY);
            user.setProfileList(
                    JsonParser.parseSimpleDataList(
                            body.optJSONArray(JsonKey.PROFILELIST)
                    )
            );
            user.setCreditsList(
                    JsonParser.parseSimpleDataList(
                            body.optJSONArray(JsonKey.CREDITLIST)
                    )
            );
            return user;
        }

        @Override
        public void onResponse(User response) {
            if (userId == getUser().getUserId()) {
                AppContext.getInstance().setUser(response);
            }
            getAdapter().notifyDataSetChanged();
        }
    };
}
